package com.jmda.platform.repository.form.service;

import com.jmda.platform.commom.BaseService;
import com.jmda.platform.commom.ResourcePathConfig;
import com.jmda.platform.commom.SequenceService;
import com.jmda.platform.commom.util.FileUtil;
import com.jmda.platform.database.DataBaseService;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.RespositoryConstant;
import com.jmda.platform.repository.application.model.ApplicationModel;
import com.jmda.platform.repository.application.service.ApplicationSevice;
import com.jmda.platform.repository.form.cache.FormCache;
import com.jmda.platform.repository.form.model.FormMetadataButtonModel;
import com.jmda.platform.repository.form.model.FormMetadataMapModel;
import com.jmda.platform.repository.form.model.FormMetadataModel;
import com.jmda.platform.repository.form.model.FormModel;
import com.jmda.platform.repository.mybatis.service.MybatisXmlMappersService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;


@Service
public class FormService implements BaseService<FormModel> {
	@Resource
	FormCache cache;
	@Resource
	SequenceService seq;
	@Resource
	ResourcePathConfig resourceLoaderPath;
	@Resource
	MybatisXmlMappersService mybatis;
	@Resource
	ApplicationSevice applicationSevice;
	@Override
	public List<FormModel> getAll() throws ResositoryException {
		// TODO Auto-generated method stub
		return cache.getAll();
	}

	@Override
	public FormModel get(String id) throws ResositoryException {
		// TODO Auto-generated method stub
		return cache.get(id);
	}

	@Override
	public void remove(String id) throws ResositoryException {
		// TODO Auto-generated method stub
		try {
			FormModel model = get(id);
			String temepleteName = model.getTemplete_name();
			// TODO 得考虑下 被多引用不能删除的问题
			ApplicationModel appModel = applicationSevice.get(model.getApplication_id());
			String eformPath = resourceLoaderPath.getTemplateEformPath()+appModel.getXieyin_code()+ File.separator;
			FileUtil.removeFile(eformPath+temepleteName);
			FileUtil.removeFile(cache.getFilePath() + id + ".xml");
			FileUtil.removeFile(cache.getFilePath() + id + "_dao.xml");
			Object[] params = {id};
			cache.remove(id);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new ResositoryException(e);
		}
	}

	@Override
	public String store(FormModel model) throws ResositoryException {
		// TODO Auto-generated method stub
		if (model.getId() == null || model.getId().trim().length() == 0) {
			model.setId(seq.getUUID());
		}
		// 指定编码解析器
		XStream xstream = new XStream(new DomDriver("utf-8"));
		// 如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
		xstream.processAnnotations(FormModel.class);
		xstream.aliasSystemAttribute(null, "class");
		String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + xstream.toXML(model);
		try {
			FileUtil.write(cache.getFilePath() + model.getId() + ".xml", xmlString);
			cache.put(model);
		} catch (IOException e) {
			throw new ResositoryException(e);
		}
		/*try {
			Object[] params = {model.getId()};
			
			List<FormDBModel> list = db.queryList("select FORM_ID from mda_form where FORM_ID = ?", FormDBModel.class, params);
			if(list!=null&&list.size()>0){
				Blob blob = new SerialBlob(xmlString.getBytes());//String 转 blo //Hibernate.createBlob(content.getBytes());  
			    Object[] upParams = {blob,model.getId()};
			    db.update("update mda_form set XML_CONTENT = ? where FORM_ID = ?", upParams);
			}else{
				Blob blob = new SerialBlob(xmlString.getBytes());
				Object[] upParams = {model.getId(),model.getName(),blob};
				db.update("insert into mda_form(FORM_ID,NAME,XML_CONTENT) values(?,?,?)", upParams);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return model.getId();
	}

	public void saveMybaits(FormMetadataModel formMetadata) throws ResositoryException, IOException {
		Map<String, Object> tmpMap = new HashMap<String, Object>();
		String form_id = formMetadata.getForm_id();
		tmpMap.put("id",form_id);
		tmpMap.put("metadataList", cache.get(form_id).getFormMetadataList());
		mybatis.storeForm(cache.getFilePath(),tmpMap);
	}

	public void remveMybaits(FormMetadataModel formMetadata) throws ResositoryException, IOException {
		mybatis.remove(cache.getFilePath(), formMetadata.getId());
	}

	public String create(String name, String applicationId, String xieyin_code) throws ResositoryException {
		// TODO Auto-generated method stub
		FormModel model = new FormModel();
		model.setId(seq.getUUID());
		model.setName(name);
		model.setApplication_id(applicationId);
		model.setXieyin_code(xieyin_code);
		List<FormMetadataModel> list = new ArrayList<FormMetadataModel>();
		model.setFormMetadataList(list);
		FormMetadataModel masterFormMetadata = new FormMetadataModel();
		masterFormMetadata.setId(seq.getUUID());
		masterFormMetadata.setXieyin_code(xieyin_code);
		masterFormMetadata.setName(name);
		masterFormMetadata.setType(RespositoryConstant.SYS_FORM_METADATA_TYPE_MASTER);
		masterFormMetadata.setSql("");
		List<FormMetadataButtonModel> formMetadataButtonList = new ArrayList<FormMetadataButtonModel>();
		FormMetadataButtonModel formMetadataButtonModelAdd = new FormMetadataButtonModel();
		formMetadataButtonModelAdd.setId(seq.getUUID());
		formMetadataButtonModelAdd.setOrderIndex(getFormMetadataButtonNextIndex(masterFormMetadata));
		formMetadataButtonModelAdd.setHandler("saveData();");
		formMetadataButtonModelAdd.setIconCls("btn btn-success");
		formMetadataButtonModelAdd.setTitle("保存");
		formMetadataButtonModelAdd.setIconClsChild("fa fa-check right");
		FormMetadataButtonModel formMetadataButtonModelSubmit = new FormMetadataButtonModel();
		formMetadataButtonModelSubmit.setId(seq.getUUID());
		formMetadataButtonModelSubmit.setOrderIndex(getFormMetadataButtonNextIndex(masterFormMetadata)+1);
		formMetadataButtonModelSubmit.setHandler("submitForm();");
		formMetadataButtonModelSubmit.setIconCls("btn btn-success");
		formMetadataButtonModelSubmit.setTitle("提交");
		formMetadataButtonModelSubmit.setIconClsChild("fa fa-check right");
		FormMetadataButtonModel formMetadataButtonModelCancel = new FormMetadataButtonModel();
		formMetadataButtonModelCancel.setId(seq.getUUID());
		formMetadataButtonModelCancel.setOrderIndex(getFormMetadataButtonNextIndex(masterFormMetadata)+2);
		formMetadataButtonModelCancel.setHandler("cancel();");
		formMetadataButtonModelCancel.setIconCls("btn btn-danger");
		formMetadataButtonModelCancel.setTitle("取消");
		formMetadataButtonModelCancel.setIconClsChild("btn-label glyphicon glyphicon-remove");
		formMetadataButtonList.add(formMetadataButtonModelAdd);
		formMetadataButtonList.add(formMetadataButtonModelSubmit);
		formMetadataButtonList.add(formMetadataButtonModelCancel);
		masterFormMetadata.setFormMetadataButtonList(formMetadataButtonList);
		list.add(masterFormMetadata);
		store(model);
		return model.getId();
	}
	public String create(FormModel model) throws ResositoryException {
		// TODO Auto-generated method stub
		store(model);
		return model.getId();
	}
	
	@Override
	public List<FormModel> queryList(FormModel param) {
		// TODO Auto-generated method stub
		return cache.queryList(param);
	}

	@Override
	public FormModel queryOne(FormModel param) {
		// TODO Auto-generated method stub
		return cache.queryList(param).get(0);
	}
	
	public int getFormMetadataButtonNextIndex(FormMetadataModel formMetadataModel) {
		List<FormMetadataButtonModel> list = formMetadataModel.getFormMetadataButtonList();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<FormMetadataButtonModel>() {
				public int compare(FormMetadataButtonModel arg0, FormMetadataButtonModel arg1) {
					return arg1.getOrderIndex() - arg0.getOrderIndex();
				}
			});
			return list.get(0).getOrderIndex()+1;
		}
		return 0;
	}
	
	
	public int getFormMetadataMapNextIndex(FormMetadataModel formMetadataModel) {
		List<FormMetadataMapModel> list = formMetadataModel.getFormMetadataMapList();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<FormMetadataMapModel>() {
				public int compare(FormMetadataMapModel arg0, FormMetadataMapModel arg1) {
					return arg1.getIndex() - arg0.getIndex();
				}
			});
			return list.get(0).getIndex()+1;
		}
		return 0;
	}

}
